|
|
|
|
|
|
|
When you use these functions, the number of characters specified must be a number greater than or equal to zero. If you enter 0, a zero-length string is returned. If the number of characters is greater than the length of the input string, the entire string is returned. |
|
|
|
|
|
|
|
|
You will find, as you write programs that manipulate strings, that the Left and Right functions are often used in conjunction with the other string functions. This is illustrated in Listing 9.5, which retrieves the first name of a person from the full name. This function is used to print name tags for an organization's events. The function assumes that the person's first and last names are separated by a space. The function then looks for a space in the input text, and upon finding the space, it extracts the characters preceding the space and supplies those characters as the first name. If no spaces appear in the input string, the function assumes that only a first name was entered. |
|
|
|
|
|
|
|
|
Listing 9.5 INSTREX.ZIPUsing the InStr and Left Functions to Extract a Person's First Name |
|
|
|
|
|
|
|
|
Dim sName As String
Dim sFirstName As String
Dim nSpacePos As Integer
sName = Trim$(txtName.Text)
nSpacePos = InStr(sName, " ")
If nSpacePos > 0 Then
sFirstName = Left$(sName, nSpacePos - 1)
lblname = "Hello, my name is " & sFirstName
End If |
|
|
|
|
|
|
|
|
Mid is another function that is used to retrieve a substring from a string, and it works in a similar manner to the Left and Right functions, but it has one additional argument. You can use the Mid function to retrieve a letter, word, or phrase from the middle of a string. |
|
|
|
|
|
|
|
|
The Mid function contains two required arguments and one optional argument, as shown in the following syntax: |
|
|
|
|
|
|
|
|
newstr = Mid(sourcestr, startpos[, numchars]) |
|
|
|
|
|
|
|
|
Startpos represents the character position at which the retrieved string begins. If startpos is greater than the length of the string, an empty string is returned. The optional argument numchars represents the number of characters to be returned from the sourcestr. If numchars is omitted, the function returns all characters in the source string, from the starting position, on to the end. The following are some examples of the Mid function: |
|
|
|
|
|
|
|
|
Print Mid("Robert Allen",8) 'Returns "Allen"
Print Mid("Robert Allen",8,2) 'Returns "Al" |
|
|
|
|
|